package com.chookss.tiku

import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.text.Html
import android.text.format.DateUtils
import android.view.KeyEvent
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProviders
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.chookss.R
import com.chookss.home.myTest.MyTestsDetailResultActivity
import com.chookss.tiku.entity.MyExam
import com.chookss.tiku.entity.Subject
import com.chookss.tiku.response.SimulateSubmit
import com.chookss.tools.MyToast
import com.chookss.tools.NavigationTools
import com.chookss.tools.Utils
import com.johnrambo.ktea.ktExtends.ShareUtils
import com.johnrambo.ktea.ktExtends.observe
import errorToast
import kotlinx.android.synthetic.main.activity_answer_exam.*
import java.io.Serializable
import java.util.*


/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2020/12/23 15:30   考试和模拟卷
 * Note:
 */
open class AnswerExamActivity : BaseSubjectActivity<AnswerExamViewModel>() {
    var answerType: String = "2"//1正式考试2模拟卷
    override fun subjectView() = subjectView
    var memoryAdapter: BasePracticeTestActivity.TitleAdapter? = null
    private val memoryList = ArrayList<HashMap<String, String>>()
    override fun createViewModel(): AnswerExamViewModel {
        return ViewModelProviders.of(this).get(AnswerExamViewModel::class.java).apply {
            examCode = exam?.examCode
            mContext = this@AnswerExamActivity
        }
    }

    protected val exam by lazy {
        var s = intent?.getSerializableExtra("exam")
        answerType = intent?.getStringExtra("answerType") ?: "2"
        if (s == null) null else s as MyExam
    }

    //考试倒计时
    var timer: CountDownTimer? = null//
    var startTimeMills = 0L
    var totalTimeMills = 0L
    var couldUseTimeMills = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_answer_exam)
        initState()
        if (subjectView != null) {
            subjectView?.showSubmit = false
            subjectView?.showSubjectNext = 6
        }
        if (exam == null) {
            println("=========")
            finish()
            return
        }
        if (!Utils.isNull(exam?.examTimeLength)) {
            totalTimeMills = (exam?.examTimeLength ?: "0").toInt() * DateUtils.MINUTE_IN_MILLIS
        }

        tvActivityTitle.text = exam!!.examName

        var myAnswerMap: Map<Int, SimulateSubmit.Answer>? = null
        savedInstanceState?.getSerializable("myAnswerMap")?.let {
            myAnswerMap = it as Map<Int, SimulateSubmit.Answer>
        }

        if (myAnswerMap?.isNotEmpty() == true) {
            viewModel.myAnswerMap.clear()
            viewModel.myAnswerMap.putAll(myAnswerMap!!)
        }
        ivLeft.setOnClickListener {
            if ("1".equals(answerType)) {
                quit()
            } else {
                finish()
            }

        }

//        btnSubmit.setOnClickListener {
//            if (viewModel.hasAnswerAll()) {
//                submitAnswers(totalTimeMills - millisUntilFinished())
//            } else {
//                AlertDialog.Builder(this@AnswerExamActivity)
//                    .setCancelable(false)
//                    .setTitle("还有题目没有作答,是否交卷")
//                    .setPositiveButton("交卷") { _: DialogInterface, i: Int ->
//                        submitAnswers(totalTimeMills - millisUntilFinished())
//                    }
//                    .setNegativeButton("取消", null)
//                    .show()
//            }
//        }
//
//        btnCard.setOnClickListener {
//            var subjects = viewModel.subjectList
//            if (subjects?.size ?: 0 == 0) {
//                return@setOnClickListener
//            }
//            DatikaDialog(this).setItems(subjects, viewModel.myAnswerMap) { _, which ->
//                gotoSubject(which)
//            }.show()
//        }
        btnCard.setOnClickListener {
            toCard()
        }

        btnNext.setOnClickListener {

            var it = viewModel.subjectList
            if (it?.size ?: 0 > subjectIndex + 1) {
                if (subjectIndex + 2 == it.size) {
                    btnNext.text = "查看答题卡"
                }
                gotoSubject(subjectIndex + 1)
                ShareUtils().putInt(this,exam?.examCode+"_index",subjectIndex + 1)
            } else {
                toCard()
            }
        }
        btnPrev.setOnClickListener {
            if (subjectIndex > 0) {
                btnNext.text = "下一题"
                gotoSubject(subjectIndex - 1)
                ShareUtils().putInt(this,exam?.examCode+"_index",subjectIndex - 1)
            }else{
                MyToast.show("已经是第一题了")
            }
        }

        subjectView().myAnswersLiveData.observe(this, { list ->
            viewModel.putMyAnswer(this,subjectIndex, list)
        })
        if("1".equals(answerType)){
            //考试
            NavigationTools.setWaterMark(this, "7")
        }else{
            //题库模拟卷
            NavigationTools.setWaterMark(this, "1")
        }
       var answer=ShareUtils().getString(this,exam?.examCode+"_answer","");
        if(!Utils.isNull(answer)){
            viewModel.myAnswerMap.clear()
            viewModel.myAnswerMap=stringToDatas(answer)
        }

    }

    override fun onContentChanged() {
        var index=ShareUtils().getInt(this,exam?.examCode+"_index",0);
        if(index>0){
            gotoSubject(index)
        }else{
            gotoSubject(0)
        }
    }
    fun stringToDatas(string: String) : HashMap<Int, SimulateSubmit.Answer> {
        val map= object : TypeToken<HashMap<Int, SimulateSubmit.Answer>>() {}.type
        return Gson().fromJson(string, map)
    }
    fun toCard() {
        //进入答题卡页面
        var subjects = viewModel.subjectList
        var selectedList: ArrayList<String> = ArrayList()
        var intent = Intent(this, AnswerCardActivity::class.java)
        intent.putExtra("subjects", subjects as Serializable?)
        viewModel.myAnswerMap?.forEach {
            selectedList.add(it.value.subjectCode)
        }
        intent.putStringArrayListExtra("selectedList", selectedList);
        intent.putExtra("title", tvActivityTitle.text.toString())
        var timeUsed = System.currentTimeMillis() - startTimeMills
        intent.putExtra("couldUseTimeMills", Math.max(couldUseTimeMills - timeUsed, 0))
        startActivityForResult(intent, 1)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 1) {
            if (data != null) {
                var index: Int = data.getIntExtra("index", 0)
                gotoSubject(index)
                ShareUtils().putInt(this,exam?.examCode+"_index",index)
                var it = viewModel.subjectList
                if (index + 1 >= it.size) {
                    btnNext.text = "查看答题卡"
                }else{
                    btnNext.text = "下一题"
                }
            }
        } else if (resultCode == 2) {
            if (viewModel.hasAnswerAll()) {
                submitAnswers(totalTimeMills - millisUntilFinished())
            } else {
                AlertDialog.Builder(this@AnswerExamActivity)
                    .setCancelable(false)
                    .setTitle("还有题目没有作答,是否交卷")
                    .setPositiveButton("交卷") { _: DialogInterface, i: Int ->
                        submitAnswers(totalTimeMills - millisUntilFinished())
                    }
                    .setNegativeButton("取消", null)
                    .show()
            }
        }
    }

    private fun millisUntilFinished(): Long {
        var timeUsed = System.currentTimeMillis() - startTimeMills
        return Math.max(couldUseTimeMills - timeUsed, 0)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if ("1".equals(answerType)) {
            quit()
        } else {
            finish()
        }

        return true
    }

    private fun quit() {
        AlertDialog.Builder(this@AnswerExamActivity)
            .setCancelable(false)
            .setTitle("提示")
            .setMessage("确定退出当前考试吗？退出后考试时间仍在计算，记得尽快回来继续答题哦")
            .setPositiveButton("确定") { _: DialogInterface, i: Int ->
                timer?.cancel()
                finish()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    override fun onDestroy() {
        super.onDestroy()
        timer?.cancel()
        if(subjectView!=null){
            Utils.hideInputKeyboard(this,subjectView)
        }
    }

    override fun initData() {
    }

    override fun onResume() {
        super.onResume()
        if (startTimeMills <= 0) {
            loadingProgress.show()
            viewModel.getExamCountDown(exam!!.examTimeLength).observe(this, {
                loadingProgress.dismiss()
                if (it.error != null) {
                    errorToast(it.error.message ?: "")
                    finish()
                } else if (it.data <= 0) {
                    errorToast("考试已经结束")
                    finish()
                } else {
                    couldUseTimeMills = it.data * 1000
                    startTimeMills = System.currentTimeMillis()
                    startAnswer()
                }
            })
        } else {
            if (millisUntilFinished() <= 0) {
                timeOver()
            } else {
                updateTime()
            }
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putSerializable("myAnswerMap", viewModel.myAnswerMap)
    }

    //开始答卷了   倒计时开始
    private fun startAnswer() {
        updateTime()
        timer?.cancel()
        timer = object : CountDownTimer(millisUntilFinished(), 1000) {
            override fun onTick(millisUntilFinished: Long) {
                updateTime()
            }

            override fun onFinish() {
                timeOver()
            }
        }
        timer?.start()
    }

    private fun timeOver() {
        timer?.cancel()
        updateTime()
        AlertDialog.Builder(this@AnswerExamActivity)
            .setCancelable(false)
            .setTitle("时间到,请交卷")
            .setPositiveButton("交卷") { _: DialogInterface, i: Int ->
                submitAnswers(totalTimeMills)
            }
            .show()
    }

    private fun updateTime() {
        var timeUsed = System.currentTimeMillis() - startTimeMills
        var millisUntilFinished = Math.max(couldUseTimeMills - timeUsed, 0)
        var minutes = millisUntilFinished / 1000 / 60
        var seconds = (millisUntilFinished - minutes * DateUtils.MINUTE_IN_MILLIS) / 1000
        tvTime.text = String.format("剩余时间: %02d:%02d", minutes, seconds)
    }


    //提交所有答案到服务器
    private fun submitAnswers(timesInMill: Long) {
        timer?.cancel()
        viewModel.submitAllAnswers(timesInMill, answerType).observe(this, {
            if (it.error != null) {
                errorToast(it.error.message ?: "")
                if (it.error.message?.contains("缺考")!!) {
                    finish()
                }
            } else {
                var intent = Intent(this, MyTestsDetailResultActivity::class.java)
                if ("2".equals(answerType)) {
                    intent.putExtra("recordType", "3")
                } else {
                    intent.putExtra("recordType", "4")
                }
                intent.putExtra("examName", tvActivityTitle.text.toString())
                intent.putExtra("pmKey", it.data.recordUid)
                intent.putExtra("examCode", it.data.examCode)
                startActivity(intent)
                finish()
            }
        })
    }


    override fun onSubjectLoaded(index: Int, subject: Subject) {
        var answer = viewModel.myAnswerMap[index]
        if (answer?.optionLvlNo == null) {
            subjectView.updateMyAnswers(null)
        } else {
            if(subject?.subjectTypeCode.equals("1004")){
                subjectView.updateMyAnswers(answer!!.optionLvlNo.split("@#^"))
            }else if(subject?.subjectTypeCode.equals("1005")){
               var value: ArrayList<String> = ArrayList()
                value.add(answer!!.optionLvlNo)
                subjectView.updateMyAnswers(value)
            }else{
                subjectView.updateMyAnswers(answer!!.optionLvlNo.split(","))
            }

        }
        val str = "<font color='#333333'> ${index + 1}" + "</font>/${viewModel.subjectList.size}"
        tvDone.text = Html.fromHtml(str)
    }

}